//
//  YYRunLoopService.m
//  YYRunLoop
//
//  Created by SMCB on 2017/11/1.
//  Copyright © 2017年 SMCB. All rights reserved.
//

#import "YYRunLoopService.h"

NS_ASSUME_NONNULL_BEGIN

static YYRunLoopService *service;

@interface YYRunLoopService ()

@property (nonatomic, strong) NSMutableSet *objectsSet;

@end

@implementation YYRunLoopService

+ (instancetype)provideService {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (nil == service) {
            service = [[super allocWithZone:NULL] init];
        }
    });
    
    return service;
}

- (id)mutableCopy {
    return [YYRunLoopService provideService];
}

- (id)copy {
    return [YYRunLoopService provideService];
}

+ (id)copyWithZone:(struct _NSZone *)zone {
    return [YYRunLoopService provideService];
}

+ (id)mutableCopyWithZone:(struct _NSZone *)zone {
    return [YYRunLoopService provideService];
}

//保证从-alloc-init和-new方法返回的对象是由shareInstance返回的
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [YYRunLoopService provideService];
}

+ (void)revokeService {
    service = nil;
}

@end

@implementation YYRunLoopService (Set)

- (void)addObject:(id)obj {
    NSParameterAssert(obj);
    if (nil != obj) {
        [self.objectsSet addObject:obj];
    }
}

- (void)removeObject:(id)obj error:(NSError *__autoreleasing  _Nullable *)error {
    NSParameterAssert(obj);
    if (nil != obj) {
        if ([self.objectsSet containsObject:obj]) {
            [self.objectsSet removeObject:obj];
        } else {
            NSError *e = [NSError errorWithDomain:[NSString stringWithFormat:@"集合中不存在--%@", obj]
                                             code:YYRunLoopServiceSetNotEixtError
                                         userInfo:@{
                                                    @"msg":[NSString stringWithFormat:@"集合中不存在--%@", obj],
                                                    @"code":@(YYRunLoopServiceSetNotEixtError)
                                                    }];
            *error = e;
        }
    } else {
        NSError *e = [NSError errorWithDomain:[NSString stringWithFormat:@"Object is nil"]
                                         code:YYRunLoopServiceObjNILError
                                     userInfo:@{
                                                @"msg":[NSString stringWithFormat:@"Object is nil"],
                                                @"code":@(YYRunLoopServiceObjNILError)
                                                }];
        *error = e;
    }
}

#pragma mark ----- setter or getter
- (NSMutableSet *)objectsSet {
    if (nil == _objectsSet) {
        _objectsSet = [[NSMutableSet alloc] init];
    }
    return _objectsSet;
}

@end

NS_ASSUME_NONNULL_END

